﻿using System;
using System.Windows.Input;

namespace ScrobbleItSL.ViewModelUtils
{
    /// <summary>
    /// Command which accepts delegates for Execute/CanExecute
    /// methods
    /// </summary>
    public class ViewModelCommand : ICommand
    {
        private readonly Action<object> executeAction;
        private readonly Predicate<object> canExecute;

        public ViewModelCommand( Action<object> executeAction ) : this(executeAction, null)
        {            
        }

        public ViewModelCommand( Action<object> executeAction, Predicate<object> canExecute )
        {
            if (executeAction == null) 
                throw new ArgumentNullException("executeAction");
            this.executeAction = executeAction;
            this.canExecute = canExecute;
        }

        public bool CanExecute( object parameter )
        {
            if (canExecute == null)
                return true;

            return canExecute( parameter );
        }

        public void Execute( object parameter )
        {
            executeAction(parameter);
        }

        public event EventHandler CanExecuteChanged;
        public void OnCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged( this, EventArgs.Empty );
            }
        }
    }
}
